package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mappper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询 获取菜品信息和分类信息
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(@RequestParam(required = false,defaultValue = "1") Integer page,
                           @RequestParam(required = false,defaultValue = "10") Integer pageSize,String name){

        //拿到分页条件
        Page<Dish> dishPage = new Page<>(page,pageSize);

        //构建菜品查询条件
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.like(name != null,Dish::getName,name);
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(dishPage,dishLambdaQueryWrapper);


        //界面需要菜品信息和分类信息 需要组合
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);

        //通过stream流
        List<DishDto> dishDtos = dishPage.getRecords().stream().map(
                dish -> {
                    DishDto dishDto = new DishDto();
                    //使用工具类将信息把菜品信息全部重装到组合类中
                    BeanUtils.copyProperties(dish, dishDto);

                    //通过菜品ID查询获取该分类名称
                    Category category = categoryService.getById(dish.getCategoryId());
                    if (category!=null){
                        //将该名字组装到组合类中
                        dishDto.setCategoryName(category.getName());
                    }
                    return dishDto;
                }

        ).collect(Collectors.toList());

        //将组装好的数据直接存入到分页类中
        dishDtoPage.setRecords(dishDtos);
        //通过查询菜品信息时获取到总条数 组装到分页类中
        dishDtoPage.setTotal(dishPage.getTotal());

        return R.success(dishDtoPage);
    }


    /**
     * 菜品保存 （逻辑逻辑）
     * 需要涉及两种表
     * 菜品表和口味表
     * @param dishDto
     * @return
     */
    @PostMapping
    public R save(@RequestBody DishDto dishDto){

        //清除rides中的数据
        Set keys = redisTemplate.keys("Dish_*");
        redisTemplate.delete(keys);

        dishService.saveDishWithFlavor(dishDto);
        return R.success();
    }

    /**
     * 根据ID数据回显
     * 需要回显菜品信息和口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> selectById(@PathVariable Long id){
        DishDto dishDto = dishService.dishWithFlavor(id);

        return R.success(dishDto);
    }

    /**
     * 修改菜品信息（逻辑外键）
     * 此时还需要修改口味信息（先根据id删除所有口味，再添加口味信息）
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto){

        //清除rides中的数据
        Set keys = redisTemplate.keys("Dish_*");
        redisTemplate.delete(keys);

        boolean b = dishService.updateDish(dishDto);
        if (!b){
            return R.error("修改失败，请稍后再试");
        }

        return R.success();
    }

    /**
     * 修改菜品状态
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status,@RequestParam("ids") List<Long> ids){

        //清除rides中的数据
        Set keys = redisTemplate.keys("Dish_*");
        redisTemplate.delete(keys);

        dishService.updateStatusByIds(status,ids);

        return R.success();
    }


    /**
     * 根据ID批量删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteDishs(@RequestParam("ids") List<Long> ids){

        //清除rides中的数据
        Set keys = redisTemplate.keys("Dish_*");
        redisTemplate.delete(keys);


        boolean flag = dishService.deleteDishWithFlavors(ids);
        if (!flag){
            return R.error("删除失败");
        }
        return R.success();
    }

    /**
     * 根据分类id展示菜品信息
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId){

        //redis优化
        //准备好key
        String key = "Dish_" + categoryId;
        //从rides中获取到
        List<DishDto> redisDishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果存在直接返回存入redis的数据
        if (redisDishDtos != null){
            return R.success(redisDishDtos);
        }

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(categoryId != null,Dish::getCategoryId,categoryId);
        lambdaQueryWrapper.eq(Dish::getStatus,1);

        List<Dish> dishes = dishService.list(lambdaQueryWrapper);

        List<DishDto> dishDtos = dishes.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);

            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(list);

            return dishDto;
        }).collect(Collectors.toList());

        //将第一次的数据存入redis中 并设置过期时间 防止非热点数据占用缓存
        redisTemplate.opsForValue().set(key,dishDtos,24, TimeUnit.HOURS);

        return R.success(dishDtos);
    }
}
